import threading
import time

import serial#导入串口通信库

class LightSource():
    def __init__(self):
        self.serial=serial.Serial()
        self.serial.port = 'com6'
        self.serial.baudrate = 19200
        self.serial.bytesize = 8
        self.serial.stopbits = 1
        self.serial.parity = "N"  # 奇偶校验位
        self.serial.open()
        if (self.serial.isOpen()):
            print("光源初始化成功！")
        else:
            print("光源初始化失败！")

    def port_close(self):
        self.serial.close()
        if (self.serial.isOpen()):
            print("光源关闭失败！")
        else:
            print("光源关闭成功！")

    def Light_Open(self,light=100):
        cmd=self._Calu_Light_Value(light)
        self.send(cmd)#先设置亮度
        cmd="40 05 01 00 2A 00 01 71"
        self.send(cmd)#再开启光源

    def Light_Close(self,light=100):
        self.send("40 05 01 00 2A 00 00 70")

    def _Calu_Light_Value(self,input_value):
        """

        Args:
            input_value:光源0-255

        Returns:下发的指令

        """
        # 将输入值限制在0到255之间
        input_value = max(0, min(input_value, 255))

        # 将输入值转换为十六进制格式，并保留两位
        hex_input_value = "{:02X}".format(input_value)

        # 构建十六进制字符串
        hex_string = "40 05 01 00 1A 00 {}".format(hex_input_value)

        # 将十六进制字符串转换为整数列表
        hex_list = [int(x, 16) for x in hex_string.split()]

        # 计算累加和
        checksum = sum(hex_list)

        # 取低8位的结果
        checksum_low_8_bits = checksum & 0xFF

        # 将校验和加入到字符串的末端
        hex_string_with_checksum = hex_string + " {:02X}".format(checksum_low_8_bits)

        return hex_string_with_checksum


    def Light_Blink_Mode(self,enable=False,times=0.1,count=None,Light=50,endoff=True):
        self.startBlink=enable
        self.times=times
        self.count=count
        self.blinklight=Light
        self.endoff=endoff
        if(enable==True):
            self.thread = threading.Thread(target=self._Blink_Thread)
            self.thread.start()
        else:
            return
    def _Blink_Thread(self):
        isOpen=True
        count=0
        while(self.startBlink):
            count=count+1
            if(count==self.count):
                break
            time.sleep(self.times)
            if(isOpen):
                self.Light_Open(self.blinklight)
            else:
                self.Light_Close()
            isOpen= not isOpen
        time.sleep(self.times)
        if(self.endoff==True):
            self.Light_Close()
        else:
            self.Light_Open(self.blinklight)

    def send(self,hexdata):
        if (self.serial.isOpen()):
            d = bytes.fromhex(hexdata)
            self.serial.write(d)  # 编码
        else:
            print("光源发送失败！")

# L=LightSource()
# L.Light_Blink_Mode(enable=True,times=0.01,count=100)
# while(True):
#     None
#
# L.Light_Open(10)
# time.sleep(1)
# L.Light_Close()
# L.port_close()